<template>
  <div>
    <!-- 扫码分享 -->
    <div class="dialog-share-container">
      <el-dialog :visible.sync="dialogVisible" lock-scroll width="1020px" top="0" title="单据分享">
        <div style="width: 100%; display: flex; position: relative">
          <div class="close" @click="hide()">
            <i style="font-size: 22px; color: white" class="el-icon-close"></i>
          </div>
          <div class="dialog-share">
            <div class="qr-container">
              <!-- 二维码 -->
              <div class="qr-code" id="qqq">
                <div style="margin: 0 auto" id="qrcode1" ref="qrCodeUrl1"></div>
              </div>
              <div class="qr-text">打开微信，扫码分享给客户</div>
            </div>
            <!-- 分享页面内容设置 -->
            <div class="page-setUp">
              <div class="page-setUp-title">分享页面内容设置</div>
              <a-divider style="margin: 10px 0 16px 0" />

              <!-- ---其他项设置--- -->
              <div class="setting-item" v-for="(item, index) in settingItems" :key="index">
                <div class="setting-checkbox" @click="toggleSetting(item.key)">
                  <img
                    width="100%"
                    :src="require(`@/assets/${shareSetting[item.key] ? 'selected' : 'not_selected'}.png`)"
                  />
                </div>
                <div style="flex: 1" :style="{ color: shareSetting[item.key] ? '#1a93fa' : '#333333' }">
                  <span>{{ item.title }}</span>
                  <a-divider style="margin: 10px 0 16px 0" />
                </div>
              </div>

              <!-- 显示收款码 -->
              <div class="setting-item" v-if="'share' in orderData">
                <div class="setting-checkbox" @click="toggleSetting('showPaymentQrCode')">
                  <img width="100%" v-if="shareSetting.showPaymentQrCode" src="@/assets/selected.png" alt="" />
                  <img width="100%" v-else src="@/assets/not_selected.png" alt="" />
                </div>
                <div style="flex: 1" :style="{ color: shareSetting.showPaymentQrCode ? '#1a93fa' : '#333333' }">
                  <div style="display: flex; align-items: center">
                    <span>显示收款码</span>
                    <!-- 上传的收款码图片 -->
                    <div v-show="false" ref="paymentQr">
                      <vue-qr
                        qid="payment"
                        :callback="test"
                        :logoSrc="logoSrc"
                        :text="paymentUrl"
                        :size="97"
                        :margin="0"
                        :logoScale="0.26"
                        :logoMargin="1"
                        :correctLevel="3"
                      ></vue-qr>
                    </div>
                    <div
                      v-if="attachments"
                      style="display: flex; flex-wrap: wrap; margin-left: 62px; position: relative"
                    >
                      <!-- v-for="(item, index) in attachments" :key="index" -->
                      <div class="attachment_view">
                        <el-image
                          style="width: 100%; height: 100%; border-radius: 3px"
                          :src="attachments"
                          :preview-src-list="[attachments]"
                        >
                        </el-image>
                        <div class="attachment_mask">
                          <img src="@/assets/att_del.png" style="width: 100%; height: 100%" @click="delAttachment()" />
                        </div>
                        <div class="attachment_mask_pre">
                          <img src="@/assets/att_pre.png" />
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-if="!attachments">
                    <div style="margin-top: 10px">
                      <span style="color: #666666; margin-right: 28px">已有其他收款码，展示需收费</span>
                      <el-button
                        type="primary"
                        size="mini"
                        style="padding-left: 20px; padding-right: 20px"
                        @click="uploadCode('payment', 'other')"
                      >
                        上传
                      </el-button>
                    </div>
                    <div style="margin-top: 20px">
                      <span style="color: #666666; margin-right: 40px">用我们的收款码，免费展示</span>
                      <el-button
                        v-if="paymentApply"
                        type="primary"
                        size="mini"
                        style="padding-left: 20px; padding-right: 20px"
                        @click="applyCode(1)"
                      >
                        申请
                      </el-button>
                      <!-- <el-button
                        type="primary"
                        size="mini"
                        style="padding-left: 20px; padding-right: 20px"
                        @click="uploadCode('payment', 'our')"
                      >
                        上传
                      </el-button> -->
                    </div>
                  </div>

                  <a-divider style="margin: 10px 0 16px 0" />
                </div>
              </div>

              <!-- 显示小程序商城二维码 -->
              <div class="setting-item">
                <div class="setting-checkbox" @click="toggleSetting('showMiniProgramQrCode')">
                  <img width="100%" v-if="shareSetting.showMiniProgramQrCode" src="@/assets/selected.png" alt="" />
                  <img width="100%" v-else src="@/assets/not_selected.png" alt="" />
                </div>
                <div style="flex: 1" :style="{ color: shareSetting.showMiniProgramQrCode ? '#1a93fa' : '#333333' }">
                  <div style="display: flex; align-items: center">
                    <span>显示小程序商城二维码</span>
                    <!-- 上传的小程序商城图片 -->
                    <div
                      v-if="smallProgramImg"
                      style="display: flex; flex-wrap: wrap; margin-left: 2px; position: relative"
                    >
                      <!-- v-for="(item, index) in smallProgramImg" :key="index" -->
                      <div class="attachment_view">
                        <el-image
                          style="width: 100%; height: 100%; border-radius: 3px"
                          :src="smallProgramImg"
                          :preview-src-list="[smallProgramImg]"
                        >
                        </el-image>
                        <div class="attachment_mask">
                          <img
                            src="@/assets/att_del.png"
                            style="width: 100%; height: 100%"
                            @click="delSmallProgramImg()"
                          />
                        </div>
                        <div class="attachment_mask_pre">
                          <img src="@/assets/att_pre.png" />
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-if="!smallProgramImg">
                    <div style="margin-top: 10px">
                      <span style="color: #666666; margin-right: 40px">有其他商城码，展示需收费</span>
                      <el-button
                        type="primary"
                        size="mini"
                        style="padding-left: 20px; padding-right: 20px"
                        @click="uploadCode('smallProgram', 'other')"
                      >
                        上传
                      </el-button>
                    </div>
                    <div style="margin-top: 20px">
                      <span style="color: #666666; margin-right: 40px">用我们的商城码，免费展示</span>
                      <el-button
                        v-if="smallProgramApply"
                        type="primary"
                        size="mini"
                        style="padding-left: 20px; padding-right: 20px"
                        @click="applyCode(2)"
                      >
                        申请
                      </el-button>
                      <!-- <el-button
                        type="primary"
                        size="mini"
                        style="padding-left: 20px; padding-right: 20px"
                        @click="uploadCode('smallProgram', 'our')"
                      >
                        上传
                      </el-button> -->
                    </div>
                  </div>
                  <a-divider style="margin: 10px 0 16px 0" />
                </div>
              </div>
            </div>
            <!-- 保存 -->
            <el-button type="primary" style="width: 85%" @click="saveSetting">保存设置</el-button>
          </div>
          <div style="width: 50%; background-color: #999; display: flex; justify-content: center; align-items: center">
            <div style="text-align: center">
              <div style="text-align: center; margin-top: 10px; color: white; margin-bottom: 35px; font-weight: bold">
                效果预览
              </div>
              <img src="@/assets/share_preview.png" style="width: 220px" />
            </div>
          </div>
        </div>
      </el-dialog>
    </div>

    <!-- 客户确认信息 -->
    <div class="dialog-result">
      <el-dialog :visible.sync="dialogResult" lock-scroll width="600px" title="客户确认信息">
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 5px 0 20px;
            height: 52px;
            border-bottom: #efefef solid 1px;
          "
        >
          <div style="font-weight: 500; color: #333; font-size: 16px">客户确认信息</div>
          <div class="close-normal" @click="hideResult()">
            <i style="font-size: 22px" class="el-icon-close"></i>
          </div>
        </div>
        <div style="width: 100%; height: 320px; display: flex; padding: 10px 30px">
          <div style="width: 270px; height: 100%; display: flex; flex-direction: column">
            <div style="color: #999; margin: 10px 0">客户反馈记录</div>
            <div style="flex: 1; overflow: hidden; overflow-y: auto" v-if="resultList.length > 0">
              <div v-for="item in resultList" :key="item.id" class="list-item">
                <img src="@assets/avatar.png" style="width: 22px; height: 22px; margin: 4px 10px 0 0" />
                <div>
                  <span style="color: #333; font-size: 13px; margin-right: 5px">{{ item.companyName }}</span>
                  <span style="font-size: 13px" :style="{ color: item.recordType == 2 ? '#f06127' : '#333' }">{{
                    item.text
                  }}</span>
                  <div>
                    <span style="font-size: 11px; color: #999">{{ item.createTime }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="list-item" style="color: #999; justify-content: center">无记录</div>
          </div>
          <div style="width: 270px; height: 100%; padding: 0 30px; overflow: hidden">
            <div>
              <div style="margin: 10px 0; color: #999">电子签名</div>
              <!-- <img :src="signatureUrl" style="width: 200px" /> -->
              <el-image v-if="signatureUrl" style="width: 200px" :src="signatureUrl" :preview-src-list="[signatureUrl]">
              </el-image>
              <div v-else class="list-item" style="color: #999; justify-content: center">未签名</div>
            </div>
          </div>
        </div>
        <div style="text-align: center; padding: 20px">
          <el-button type="primary" style="width: 90px" @click="hideResult()">确定</el-button>
          <el-button style="width: 90px" @click="hideResult()">取消</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 申请收款码/小程序码弹窗 -->
    <dialog-apply ref="applyCode" @changeApplyBtn="changeApplyBtn"></dialog-apply>

    <!-- 上传其他的收款码/小程序码弹窗 -->
    <dialog-upload ref="uploadCode" @uploadImg="uploadImg"></dialog-upload>
  </div>
</template>

<script>
import logoSrc from '@/assets/logo.png'
import VueQr from 'vue-qr'
import QRCode from 'qrcodejs2'
import { mapGetters } from 'vuex'
import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID, USER_INFO, ACCOUNT_BOOK } from '@/store/mutation-types'
import { getAction, postAction } from '../../api/manage'
import { color } from 'echarts'
import dialogApply from './dialogApply.vue'
import dialogUpload from './dialogUpload.vue'

export default {
  components: { dialogApply, dialogUpload, VueQr },
  name: 'dialogShare',
  computed: {
    ...mapGetters(['name']),
  },
  created() {},
  updated() {},
  data() {
    return {
      dialogVisible: false, // 新增弹框
      dialogResult: false,
      resultList: [],
      signatureUrl: '',

      orderData: {},

      settingItems: [
        {
          title: '显示累计欠款',
          key: 'showTotalMountOwned',
        },
        {
          title: '让客户留言',
          key: 'clientMessage',
        },
        {
          title: '请客户确认信息',
          key: 'clientConfirm',
        },
      ],

      // 分享设置
      shareSetting: {
        clientConfirm: false,
        clientMessage: false,
        showMiniProgramQrCode: false,
        showPaymentQrCode: false,
        showTotalMountOwned: false,
        paymentQrCode: '',
      },

      // 申请按钮
      paymentApply: true,
      smallProgramApply: true,

      // 上传的收款码图片
      attachments: '',
      smallProgramImg: '',

      paymentUrl: '',
      qrCodeImageUrl: '',
      logoSrc,
    }
  },
  methods: {
    // xghOrderRecord/xghOrderRecord/getConfig
    getConfig(params) {
      let obj = {}
      let arr = params.split('&')
      arr.forEach((item) => {
        let [key, value] = item.split('=')
        obj[key] = value
      })
      this.orderData = obj
      console.log('this.orderData', this.orderData)

      getAction('/xghOrderRecord/xghOrderRecord/getConfig', { orderId: obj.billId, orderType: obj.orderType }).then(
        (res) => {
          if (res.success) {
            this.shareSetting = res.result || {}
            if (res.result && res.result.paymentQrCode) {
              this.attachments = res.result.paymentQrCode
            }
            if (res.result && res.result.miniProgramQrCode) {
              this.smallProgramImg = res.result.miniProgramQrCode
            }
          } else {
            this.$message.error(res.message)
          }
        }
      )
    },
    // 获取申请状态
    getApplyState() {
      let params = {
        accountBookId: Vue.ls.get(ACCOUNT_BOOK).id,
      }
      console.log(params)
      getAction('/xghRequestForm/xghRequestForm/accountInfo', params).then((res) => {
        if (res.success) {
          let list = res.result
          if (list.length === 0) {
            // 数组为空，两个属性都设为true
            this.paymentApply = true
            this.smallProgramApply = true
          } else {
            const hasType1 = list.some((item) => item.requestType == 1)
            this.paymentApply = !hasType1
            const hasType2 = list.some((item) => item.requestType == 2)
            this.smallProgramApply = !hasType2
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 改变申请按钮 申请过一次后按钮消失
    changeApplyBtn(type) {
      if (type === 1) {
        this.paymentApply = false
      } else {
        this.smallProgramApply = false
      }
    },
    // 上传收款码/小程序码
    uploadCode(code, status) {
      this.$refs.uploadCode.show(code, status)
    },

    uploadImg(type, img) {
      // console.log('img', type, img,typeof(img[0]))
      if (type == 'payment') {
        this.attachments = img[0]
        // console.log('this.attachments',this.attachments)
      } else {
        this.smallProgramImg = img[0]
      }
      this.saveSetting()
    },
    delAttachment() {
      // this.attachments.splice(index, 1)
      this.attachments = ''
      this.saveSetting()
    },
    delSmallProgramImg() {
      // this.smallProgramImg.splice(index, 1)
      this.smallProgramImg = ''
      this.saveSetting()
    },
    // 我们商城码 收款码申请
    applyCode(type) {
      if (type === 1) {
        // 收款码申请
        this.$refs.applyCode.show(type)
      } else {
        // 小程序码申请
        this.$router.push({ path: '/shopManage/buyShop' })
      }
    },
    // 切换分享设置
    toggleSetting(settingKey) {
      this.shareSetting[settingKey] = !this.shareSetting[settingKey]
    },

    // 保存设置 xghOrderRecord/xghOrderRecord/editConfig   saveConfig
    saveSetting() {
      let params = {
        // ...this.shareSetting,
        orderId: this.orderData.billId,
        orderType: this.orderData.orderType,
        xghShareOrderConfig: {
          clientConfirm: this.shareSetting.clientConfirm ? true : false,
          clientMessage: this.shareSetting.clientMessage ? true : false,
          showMiniProgramQrCode: this.shareSetting.showMiniProgramQrCode ? true : false,
          showPaymentQrCode: this.shareSetting.showPaymentQrCode ? true : false,
          showTotalMountOwned: this.shareSetting.showTotalMountOwned ? true : false,
          paymentQrCode: this.isBase64(this.attachments) ? '' : this.attachments,
          miniProgramQrCode: this.isBase64(this.smallProgramImg) ? '' : this.smallProgramImg,
        },
      }
      // console.log('params',JSON.parse(JSON.stringify(params)))
      postAction('/xghOrderRecord/xghOrderRecord/editConfig', params).then((res) => {
        // console.log(res)
        if (res.success) {
          this.$message.success('保存成功')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    isBase64(str) {
      if (!str) return false
      // 基础格式校验
      const hasDataHeader = str.startsWith('data:') && str.includes(';base64,')
      // 内容校验（可选）
      const base64Part = str.split(',')[1]
      const reg = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/
      return hasDataHeader && reg.test(base64Part)
    },

    // 获取申请的收款码地址
    test(dataUrl, id) {
      // console.log("二维码回调",dataUrl, id)
      if (!this.shareSetting.paymentQrCode && this.paymentUrl) {
        this.attachments = dataUrl
      }
    },

    show(params) {
      this.dialogVisible = true
      let accountBookId = Vue.ls.get(ACCOUNT_BOOK).id
      let signUrl = `https://yun.xiangguohe.cn?from=share&accountBookId=${accountBookId}&${params}`
      // 体验版
      // let signUrl = `https://yun.xiangguohe.cn?from=sss&accountBookId=${accountBookId}&${params}`
      console.log('微信小程序测试链接', signUrl)
      //取出share
      const searchParams = new URLSearchParams(params)
      const share = searchParams.get('share')
      // console.log('单号',share); // 输出：20250226162903130474973315
      if (share) {
        // 微信支付配置的是晓光的服务，没有配郭哥的，正式用晓光的。
        // 	// let paymentUrl = `http://cloudjinxiaocun.good-software.cn/#/?orderNumber=${orderNumber}`
        this.paymentUrl = `http://cloudjinxiaocun.good-software.cn/#/?orderNumber=${share}&accountBookId=${accountBookId}&from=share`
        // this.paymentUrl = `http://192.168.0.181:9002/#/?orderNumber=${share}&accountBookId=${accountBookId}&from=share`
        // this.paymentUrl = `xjlx.w1.luyouxia.net/#/?orderNumber=${share}&accountBookId=${accountBookId}&from=share`
      }

      setTimeout(() => {
        // 小程序码
        document.getElementById('qrcode1').innerHTML = ''
        var qrcode = new QRCode(this.$refs.qrCodeUrl1, {
          text: signUrl,
          width: 120,
          height: 120,
          colorDark: '#333333', //二维码颜色
          colorLight: '#ffffff', //二维码背景色
          correctLevel: QRCode.CorrectLevel.H,
        })
      }, 500)
      this.getConfig(params)
      this.getApplyState()
    },

    hide() {
      this.dialogVisible = false
      document.getElementById('qrcode1').innerHTML = ''
    },
    showResult(orderId, name = '') {
      this.signatureUrl = ''
      this.resultList = []
      this.dialogResult = true
      let that = this
      getAction(`/xghOrderRecord/xghOrderRecord/list?orderId=${orderId}`).then((res) => {
        console.log(res)
        if (res.success) {
          let list = res.result || []
          that.resultList = list.map((item) => {
            item.companyName = name
            if (item.recordType == 1) {
              item.text = '查看了单据'
            } else if (item.recordType == 2) {
              item.text = '签名确认了单据信息'
              that.signatureUrl = item.content
            } else if (item.recordType == 3) {
              item.text = '给您留言:' + item.content
            }
            return item
          })
          // that.resultList = that.resultList.concat(that.resultList)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    hideResult(id) {
      this.dialogResult = false
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 0;
}
::v-deep .dialog-share-container,
.dialog-result {
  .el-dialog__header {
    display: none;
  }
}
::v-deep .el-dialog__wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}
.close {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 42px;
  height: 42px;
  padding: 10px;
  // background: red;
}
.close-normal {
  width: 42px;
  height: 42px;
  padding: 10px;
}
.list-item {
  border-top: solid #efefef 1px;
  padding: 8px 10px 8px 0;
  display: flex;
}

.dialog-share {
  width: 50%;
  height: 100%;
  background-color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  padding: 40px 70px;

  .qr-container {
    display: flex;
    flex-direction: column;
    align-items: center;

    .qr-code {
      display: flex;
      justify-content: center;
      width: 120px;
      height: 120px;
    }

    .qr-text {
      text-align: center;
      margin-top: 10px;
      margin-top: 20px;
    }
  }
  .page-setUp {
    width: 100%;
    margin-top: 30px;
    &-title {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      color: #666666;
      font-size: 13px;
    }
    .setting-item {
      display: flex;
      align-items: baseline;
      font-size: 12px;

      .setting-checkbox {
        cursor: pointer;
        width: 20px;
        height: 20px;
        margin-right: 10px;
      }
    }
  }
}

.attachment_view {
  position: absolute;
  top: -23px;
  left: 0;
  border: 1px dashed white;
  width: 40px;
  height: 40px;
  // margin-left: 17px;
  background-color: #f6f6f6;
  line-height: 40px;
  text-align: center;
  border-radius: 3px;
}

.attachment_mask {
  z-index: 2;
  position: absolute;
  right: 0;
  top: 0;
  width: 12px;
  height: 12px;
  display: flex;
  align-items: center;
}

.attachment_mask_pre {
  z-index: 1;
  position: absolute;
  display: flex;
  align-items: center;
  pointer-events: none;
  right: 0;
  top: 0;
  left: 0;
  bottom: 0;
  backdrop-filter: blur(0.5px);

  img {
    position: absolute;
    width: 14px;
    height: 14px;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
  }
}
</style>
